package cn.itcast.service.system.impl;

import cn.itcast.dao.system.UserDao;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.security.provider.MD5;


import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    /**
     * 根据企业id查询全部用户
     *
     * @param companyId 企业id
     * @return 返回用户集合
     */
    @Override
    public List<User> findAll(String companyId) {
        List<User> users = userDao.findAll(companyId);
        return users;
    }

    /**
     * 根据id查询用户
     *
     * @param userId 用户id
     * @return 返回用户对象
     */
    @Override
    public User findById(String userId) {
        User user = userDao.findById(userId);
        return user;
    }

    /**
     * 根据id删除
     *
     * @param userId 用户id
     */
    @Override
    public void delete(String userId) {
        userDao.delete(userId);
    }

    /**
     * 保存
     *
     * @param user 用户对象
     */
    @Override
    public void save(User user) {
        user.setId(UUID.randomUUID().toString());
        if (user.getPassword() != null){
            Md5Hash md5Hash = new Md5Hash(user.getPassword(), user.getEmail());
            String password= md5Hash.toString();
            user.setPassword(password);
        }
        userDao.save(user);
    }

    /**
     * 更新
     *
     * @param user 用户对象
     */
    @Override
    public void update(User user) {
        userDao.update(user);
    }

    @Override
    public PageInfo<User> findByPage(String companyId,int pageNum,int pageSize) {
        Page<User> page = PageHelper.startPage(pageNum, pageSize);
        List<User> list = userDao.findAll(companyId);
        PageInfo<User> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public List<String> findOldRole(String id) {
        List<String> oldRole = userDao.findOldRole(id);
        return oldRole;
    }

    @Override
    public void changeRole(String id, String roleId) {
        userDao.changeRole(id,roleId);
    }

    @Override
    public void cleanAllRoleByUserId(String id) {
        userDao.cleanAllRoleByUserId(id);
    }

    @Override
    public User findUserByEmail(String email) {
        User user = userDao.findUserByEmail(email);
        return user;
    }
}
